<?php
/**
* Letterman Newsletter Component
* 
* @package Letterman
* @author Soeren
* @copyright Soeren Eberhardt <soeren@virtuemart.net>
*   (who just needed an easy and *working* Newsletter component for Mambo 4.5.1 and mixed up Newsletter and YaNC)
* @copyright Mark Lindeman <mark@pictura-dp.nl> 
*    (parts of the Newsletter component by Mark Lindeman; Pictura Database Publishing bv, Heiloo the Netherland)
* @copyright Adam van Dongen <adam@tim-online.nl>
*    (parts of the YaNC component by Adam van Dongen, www.tim-online.nl)
*    
* @copyright Philip Sylvain <contact@sphilip.com>
*  	(MVC refactorization and AJAX)
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*
*/

// no direct access
defined('_JEXEC') or die();

jimport('joomla.application.component.model');

class LettermanModelSubscribers extends JModel
{
	
	var $row = null;
	
	function getId()
	{
		$cid = $this->getCid();
		
		if (empty($cid[0])) {
			//try to see id
			return JRequest::getInt('id', 0);
		}
		
		return $cid[0] ;
	}
	
	function getCid()
	{
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger( $cid, array(0) );
		
		return $cid ;
	}
	
	function &getRow()
	{
		if ( !is_object($this->row) ) {
			
			$this->row =& $this->getTable('subscribers');
			$this->row->load( $this->getId() );
		} 

		return $this->row;
	}
	
	
	function getItems()
	{
		$result = array();
		$mainframe = &JFactory::getApplication();
	
		$context = 'com_letterman.subscribers' ;
		$default_limit = $mainframe->getCfg('list_limit');
		
		$limit = $mainframe->getUserStateFromRequest( $context.'limit', 'limit', $default_limit, 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0, 'int' );
		$search = $mainframe->getUserStateFromRequest( $context.'search', 'search', '', 'string' );
		$search = $this->_db->getEscaped( trim( strtolower( $search ) ) );

		$order = $this->_db->getEscaped( JRequest::getCmd('filter_order', 'name'));
		$order_dir = $this->_db->getEscaped( JRequest::getCmd('filter_order_Dir', 'asc'));
	
		$where = '';
		if ($search) {
			$where = ' WHERE name LIKE \'%' . $search . '%\' OR email LIKE \'%' .$search . '%\'';
		}
	
		$sql = 'SELECT * FROM `#__letterman_subscribers`' . PHP_EOL . $where 
			 . PHP_EOL . 'ORDER BY ' . $order . ' ' . strtoupper( $order_dir ) ;
		
		$rows = $this->_getList( $sql , $limitstart, $limit );
	
		if ( !$this->_db->getErrorNum() ) {
	            
	        $result['limitstart'] = $limitstart ;
			$result['limit'] = $limit ; 
			$result['total'] = $this->_getListCount( $sql );
	        $result['rows'] = $rows ;
	        $result['search'] = $search ;
	        $result['order'] = $order ;
	        $result['order_dir'] = $order_dir;      
	
	    } else {
	            JError::raiseWarning( 200, $this->_db->getErrorMsg() );
	            return false;
	    }
	         
	    return $result ;
	}
	
	
	function save()
	{
		$row = & $this->getRow();
		
		$datas = array(
			'name' 		=> JRequest::getString('name', ''),
			'email' 	=> JRequest::getString('email', ''),
			'confirmed' => JRequest::getInt('confirmed' , 0)
		);
		
		if( !$id ) {
			$datas['subscribe_date'] = date( "Y-m-d h:i:s" );
		}
		
		//email validation
		jimport('joomla.mail.helper');
		
		$datas['email'] = JMailHelper::cleanAddress( $datas['email'] );
		
		if ( !JMailHelper::isEmailAddress($datas['email']) ) {
			JError::raiseWarning( 200, JText::sprintf( 'Invalid email', $datas['email'] ) );
            return false;
		}
		
		//avoid duplicate entry for email
        $query = 'SELECT id FROM `#__letterman_subscribers`'
        	   . ' WHERE email=' . $this->_db->Quote( $datas['email'] ) 
               . ' AND id <>' . intval( $id );

        if ( $this->_getListCount( $query ) > 0 ){
            
            JError::raiseWarning( 200, JText::sprintf( 'Email already exists', $datas['email'] ) );
            return false;
        }
		
		if ( !$row->bind($datas) ) {
            JError::raiseWarning( 200, $row->getError() );
            return false;
        }
       
        if ( !$row->store() ) {
            JError::raiseWarning( 200, $row->getError() );
            return false;
        }
        
        return true;
		
	}
	
	function remove()
	{
		$cids = implode( ',', $this->getCid() );
		
		$this->_db->setQuery( 'DELETE FROM `#__letterman_subscribers` WHERE id IN (' . $cids . ')' );
		
		if ( !$this->_db->query() ) {
			JError::raiseError( 500, $this->_db->getErrorMsg() );
			return false;
		}
		
		return true;
	}
	
	function removeFromEmail( $email ) {
		
		//email validation
		jimport('joomla.mail.helper');
		
		$email = JMailHelper::cleanAddress( $email );
		
		if ( !JMailHelper::isEmailAddress($email) ) {
			JError::raiseWarning( 200, JText::sprintf( 'Invalid email', $email ) );
            return false;
		}
		
		$this->_db->setQuery('SELECT id FROM #__letterman_subscribers WHERE email = ' . $this->_db->Quote($email)) ;
		
		if ( $id = $this->_db->loadResult() ){
			$this->_db->setQuery( 'DELETE FROM #__letterman_subscribers WHERE id=' . intval($id) );
			
			if (!$this->_db->query()){
        		JError::raiseWarning( 200, $this->_db->getErrorMsg() );
        		return false;
        	}
			
		} else {
			JError::raiseWarning( 200, JText::_( 'ACCOUNT_NOTFOUND' ) );
			return false;
		}
		
		return true ;
	}
	
	
	function validate( $bool )
	{
		$cid = $this->getCid();
		
		$cids = implode( ',', $cid );

		$query = 'UPDATE `#__letterman_subscribers` SET confirmed='. (int) $bool . PHP_EOL 
		       . 'WHERE id IN ( '. $cids .' )';
				
		$this->_db->setQuery($query);
		
		if (!$this->_db->query()) {
			JError::raiseError( 500, $this->_db->getErrorMsg() );
			return false;
		}
		
		return true;
	}
}
